package com.LeeCode;

import org.junit.jupiter.api.Test;

import java.util.ArrayList;
import java.util.List;

/**
 * 字符串相乘
 */

public class Code043 {
    public static void main(String[] args) {
        String num1 = "124325", num2 = "123";
        System.out.println(new Code043().multiply(num1, num2));

    }

    public String multiply(String num1, String num2) {
        if (num2.equals("0") || num1.equals("0")) {
            return "0";
        }
        List<StringBuilder> list = new ArrayList<>();
        for (int i = num2.length() - 1; i >= 0; i--) {
            list.add(singleMultiply(num1, num2.charAt(i), num2.length() - 1 - i));
        }
        StringBuilder res = new StringBuilder();
        int aux = 0, len = list.get(list.size() - 1).length();
        for (int i = 0; i < len; i++) {
            int temp = 0;
            for (int j = 0; j < list.size(); j++) {
                temp += list.get(j).length() > i ? list.get(j).charAt(i) - '0' : 0;
            }
            temp += aux;
            res.append(String.valueOf(temp % 10));
            aux = temp / 10;
        }
        if (aux > 0) {
            res.append(String.valueOf(aux));
        }
        res.reverse();

        return res.toString();
    }

    public StringBuilder singleMultiply(String num1, char c, int offset) {
        StringBuilder res = new StringBuilder();
        for (int i = 0; i < offset; i++) {
            res.append('0');
        }
        int multiplier = c - '0', aux = 0;
        for (int i = num1.length() - 1; i >= 0; i--) {
            int num = num1.charAt(i) - '0';
            int temp = multiplier * num + aux;
            aux = temp / 10;
            res.append(String.valueOf(temp % 10));
        }
        if (aux > 0) {
            res.append(String.valueOf(aux));
        }
        return res;
    }

    @Test
    public void test() {
        System.out.println(singleMultiply("123", '2', 0));
        System.out.println(singleMultiply("123", '2', 1));
        System.out.println(singleMultiply("123", '0', 1));
    }
}
